var videoModal = document.getElementById('videoModal');
var nowVideo = document.getElementById('nowVideo');
var nowMusic = document.getElementById('nowMusic');
var aplayer = document.getElementById('aplayer');
var url = 'http://' + document.domain + ':3000/v1';
var songUrl = 'http://music.163.com/song/media/outer/url?id=';
var limit = 15;//分页条数

$('.toast').toast({
    autohide: false
})
var ap;
function musicPlay(id, songName, picUrl, artist) {
    $('#musicToast').toast('show');
    $.get(this.url + '/lyric?id=' + id, function (data) {
        if (data.code == 200) {
            $('#musicToast').toast('show');
            ap = new APlayer({
                container: aplayer,
                audio: [{
                    name: songName,
                    artist: artist,
                    url: songUrl + id,
                    cover: picUrl,
                    lrc: data.uncollected ? '' : data.lrc.lyric,
                }],
                volume: 1,
                autoplay: true,
                lrcType: 1,
            });
        }
    }, 'json');
}
$('#musicToast').on('hide.bs.toast', function () {
    try { ap.pause(); } catch (e) {
        console.log('没事，小事👌');
    }
})
function mvPlay(id, songName, artist) {
    $.get(this.url + '/mv', { id: id }, function (data) {
        if (data.code == 200) {
            $('#musicToast').toast('hide');
            let resolution = Object.keys(data.data.brs);
            let i = 0;
            let mvResolution = $('#mvResolution');
            let active = '';
            $(mvResolution).html('');
            for (; i < resolution.length; i++) {
                active = (i + 1) == resolution.length ? 'active' : '';
                $(mvResolution).html($(mvResolution).html() +
                    '<button type="button" class="btn btn-primary ' + active
                    + '" data-url="' + data.data.brs[resolution[i]] + '">' + resolution[i] + 'P</button>');
            }
            $(nowVideo).attr('src', data.data.brs[resolution[i - 1]]);
            $('#videoModalTitle').html(songName + ' - ' + artist);
            nowVideo.play();
            //切换分辨率 不可独立出去，需在此注册事件，在外面神一般的找不到
            $('#mvResolution button').click(function (event) {
                let bt = event.target;
                if (!$(bt).hasClass('active')) {
                    $($('#mvResolution').contents('button')).each(function () {
                        $(this).removeClass('active');
                    })
                    $(bt).addClass('active');
                    $(nowVideo).attr('src', $(bt).data('url'));
                    $(nowVideo).on('canplay', function () {
                        nowVideo.play();
                    })
                }
            })
        } else {

        }
    }, 'json');
}

//隐藏模态框即暂停视频
$(videoModal).on('hide.bs.modal', function () {
    nowVideo.pause();
})
//mv icon拼接模板
function templateMvIcon(id, name, arName) {
    return '<button title="播放mv" data-toggle="modal" data-target="#videoModal" type="button" ' +
        'class="margin-10 btn btn-outline-danger btn-sm align-text-bottom" onclick="mvPlay(' + id + ',\'' +
        name + '\',\'' + arName + '\')">MV</button>'
}
//歌曲列表拼接模板
function templateSongList(id, No, picUrl, name, arName, mv) {
    return '<tr><th scope="row" class="line-height-300">' + (No + 1) + '</th><td>' +
        '<img align="TextTop" class="rounded cover" src="' + picUrl + '"/>' +
        '<span class="d-inline-block text-lowercase text-break margin-10 width-70">' + name + '<br/><span class="text-secondary artist-8">' + arName + '</span></span>' + mv + '</td><td>' +
        '<button type="button" data-toggle="modal" data-target="#musicModal" class="btn btn-danger btn-sm" ' +
        'onclick="musicPlay(' + id + ',\'' + name + '\',\'' + picUrl + '\',\'' + arName +
        '\')"><i class="fas fa-play"></i></button></td></tr>';
}
var nowPage = 0;//用于以下回调函数的分页知道当前的分页
function searchSong(pages) {
    nowPage = pages ? pages : 0;
    let offset = nowPage * limit;
    $.get(this.url + '/search', {
        keywords: $('#search').val(),
        limit: limit,
        offset: offset,
    }, function (data) {
        let songList = $('#songList');
        if (data.code == 200) {
            $(songList).html('');
            let result = data.result.songs;
            let mvIcon = '';
            $('#songListName').html('搜索结果');
            for (let i = 0; i < result.length; i++) {
                if (result[i].mv != 0) { mvIcon = templateMvIcon(result[i].mv, result[i].name, result[i].ar[result[i].ar.length - 1].name); };
                $(songList).html($(songList).html() + templateSongList(result[i].id, i, result[i].al.picUrl, result[i].name, result[i].ar[result[i].ar.length - 1].name, mvIcon))
                mvIcon = '';
            }
            let resultCount = data.result.songCount;
            let page = 0;
            //神一般的songCount某些时候不同
            if (resultCount % limit == 0) {
                page = Number.parseInt(resultCount / limit);
            } else {
                page = Number.parseInt(resultCount / limit) + 1;
            }
            let pageNo = $('#pageNo');
            $(pageNo).html('');
            for (let i = 0; i < page; i++) {
                status = i == nowPage ? ' active' : '';
                $(pageNo).html($(pageNo).html() +
                    '<li class="page-item' + status + '"><a class="page-link" href="javascript:{searchSong(' + i + ')}">' + (i + 1) + '</a></li>');
            }
        } else {

        }
    }, 'json');
}

function indexLoad(offset) {
    $.get(this.url + '/playlist/detail', {
        id: 3778678,
        offset: offset * limit,
        limit: limit,
    }, function (data) {
        if (data.code == 200) {
            let result = data.playlist.tracks;
            let mvIcon = '';
            $('#songListName').html(data.playlist.name);
            $(songList).html('');
            for (let i = 0; i < result.length; i++) {
                if (result[i].mv != 0) { mvIcon = templateMvIcon(result[i].mv, result[i].name, result[i].ar[result[i].ar.length - 1].name); };
                $(songList).html($(songList).html() + templateSongList(result[i].id, i, result[i].al.picUrl, result[i].name, result[i].ar[result[i].ar.length - 1].name, mvIcon))
                mvIcon = '';
            }
        } else {

        }
    }, 'json');
}
window.onload = indexLoad(0);